package com.alex.seo.contentsource;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.io.FileUtils;

import com.alex.seo.contentsource.dto.ContentDTO;
import com.alex.seo.contentsource.exeption.ContentSourceException;
import com.alex.utils.common.Random;

public class FileContentSource implements ContentSource, FilenameFilter {

	private File contentDirectory;

	private File usedContentDirectory;

	public FileContentSource(File contentDirectory, File usedContentDirectory) {
		this.contentDirectory = contentDirectory;
		this.usedContentDirectory = usedContentDirectory;
	}

	@Override
	public ContentDTO getContent() throws NoContentException, ContentSourceException {
		File[] files = contentDirectory.listFiles(this);
		if (files.length == 0) {
			throw new NoContentException("No files in directory: " + contentDirectory);
		}
		File file = files[Random.getInt(files.length)];
		try {
			String content = FileUtils.readFileToString(file);
			ContentDTO contentDTO = new ContentDTO("!!!", content, new ArrayList<String>());
			FileUtils.moveFileToDirectory(file, usedContentDirectory, false);
			return contentDTO;
		} catch (IOException e) {
			throw new NoContentException(e);
		}
	}

	@Override
	public boolean accept(File file, String name) {
		return file.isFile();
	}
}
